package com.et.util

import io.reactivex.rxjava3.core.Single
import java.io.BufferedReader
import java.io.BufferedWriter
import java.io.InputStreamReader
import java.io.OutputStreamWriter
import java.net.InetSocketAddress
import java.net.Socket

const val EOF_END = '0'

object SocketUtil {

    fun write(host: String, port: Int, content: String): Single<String> {
        return Single.create { emitter ->
            val response = StringBuilder(128)
            Socket().use { it0 ->
                it0.connect(InetSocketAddress(host, port), 20_000)
                it0.soTimeout = 15_000
                BufferedWriter(OutputStreamWriter(it0.getOutputStream())).use { it1 ->
                    it1.write(content)
                    it1.flush()
                    BufferedReader(InputStreamReader(it0.getInputStream())).use { it2 ->
                        it2.readLines().apply { if (isEmpty()) response.append(EOF_END) }.onEach { s ->
                            response.append(s)
                        }
                    }
                }
            }
            emitter.onSuccess(response.toString())
        }
    }
}
